package miniProgram

import (
	"fmt"
	"gitee.com/yizhisamoye/GoWeChat/entity/user"
	"gitee.com/yizhisamoye/GoWeChat/utils"
)

func (w WxMiniProgram) Login(code string) (*user.WxUser, error) {
	url := fmt.Sprintf(BaseUrl+"/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", w.appId, w.appSecret, code)
	result, err := utils.GetJson(url)
	if err != nil {
		return nil, err
	}
	m := new(user.WxUser)
	if openId, exist := result["openid"]; exist {
		if openId != nil {
			m.OpenId = openId.(string)
		}
	}
	if unionId, exist := result["unionid"]; exist {
		if unionId != nil {
			m.UnionId = unionId.(string)
		}
	}
	if sessionKey, exist := result["session_key"]; exist {
		if sessionKey != nil {
			m.SessionKey = sessionKey.(string)
		}
	}
	return m, nil
}
